package com.hoshiicloud.payment.controller;

import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.DigestUtils;
import com.hoshiicloud.payment.feign.DownloadService;
import com.hoshiicloud.payment.feign.UploadService;
import com.hoshiicloud.payment.sdk.wxpay.WXPayUtil;
import com.hoshiicloud.payment.service.PaymentService;
import com.hoshiicloud.payment.util.TensoonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @program: hoshiicloud
 * @description: 测试控制器
 * @author: Mr.wu
 * @create: 2019-06-05 18:15
 **/
@Api(value = "测试接口", tags = "测试接口")
@Controller
@Slf4j
@RequestMapping("/test")
public class TestController {
    @Autowired
    private UploadService uploadService;
    @Autowired
    private DownloadService downloadService;
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/testSelect")
    @ResponseBody
    public Response test(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String str = IOUtils.toString(request.getInputStream(), "UTF-8");
        log.info("接收内容:" + str);
        Map<String, String> reqData = WXPayUtil.xmlToMap(str);

        String appKey="qwert512yui698dfg123hjk456vbn459";
        String decryptionKey= DigestUtils.md5(appKey).toLowerCase();
        String encryptedData=reqData.get("req_info");
        //微信退款回调的base64解密需指定字符集
        String data= TensoonUtil.decryptData(encryptedData,decryptionKey.getBytes());

        return Response.data(data);
    }


    @PostMapping("/testUpload")
    @ApiOperation(value = "测试上传文件")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bucketName",value = "存储空间名称，上传时指定的存储空间",paramType = "String"),
            @ApiImplicitParam(name = "objectKey",value = "文件key,上传时存储的对象key，上传完毕后原样返回，如不传则使用文件MD5值。",paramType = "String"),
            @ApiImplicitParam(name = "fileName",value = "文件名,批量上传时需和key对应",paramType = "String"),
            @ApiImplicitParam(name = "folder",value = "文件夹路径",paramType = "String"),
            @ApiImplicitParam(name = "file",value = "文件",paramType = "formData",dataType = "MultipartFile"),
    })
    public Response testUpload(@RequestParam("bucketName") String bucketName, @RequestParam("objectKey") String objectKey, @RequestParam("fileName") String fileName, @RequestParam("folder") String folder,@RequestPart("file") MultipartFile file) {
        log.info("文件名:"+file.getOriginalFilename());
        //param.setFile(uploadFile);
        Response result=uploadService.fileUpload(bucketName,objectKey,fileName,folder,false,file);
        log.info(result.toString());
        return result;
    }

    @GetMapping("/testDownload")
    @ApiOperation(value = "测试下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bucketName",value = "存储空间名称，上传时指定的存储空间",paramType = "String"),
            @ApiImplicitParam(name = "objectKey",value = "文件key,上传时存储的对象key，上传完毕后原样返回，如不传则使用文件MD5值。",paramType = "String"),
    })
    public void testDownload(@RequestParam("bucketName") String bucketName, @RequestParam("objectKey") String objectKey, HttpServletResponse response) throws Exception {
        //param.setFile(uploadFile);
        feign.Response result=downloadService.fileDownload(bucketName,objectKey);
        if(result==null){
            log.info("文件下载失败");
            return;
        }
        feign.Response.Body body=result.body();
        InputStream inputStream=body.asInputStream();
        String realFileName="";
        String[] strArr=realFileName.split("/");
        if(strArr.length>0){
            realFileName=strArr[strArr.length-1];
        }
        else{
            realFileName=objectKey;
        }
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName, "UTF-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download the song successfully!");
        }
        catch (Exception e) {
            System.out.println("Download the song failed!");
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info(result.toString());
    }
}
